/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package org.rcs.servlets.utils;

import java.io.UnsupportedEncodingException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;

/**
 *
 * @author ruben
 */
public class CustomHttpServletRequest extends HttpServletRequestWrapper {

  public CustomHttpServletRequest(HttpServletRequest delegate) {
    super(delegate);
  }

  @Override
  public String getParameter(String name) {
    return convertToEncoding(super.getParameter(name));
  }

  @Override
  public String[] getParameterValues(String name) {
    String[] result = super.getParameterValues(name);

    if (null != result)
      for (int i = 0; i < result.length; ++i)
        result[i] = convertToEncoding(result[i]);

    return result;
  }

  @Override
  public String getPathInfo() {
    String uri = getRequestURI();
    String context = getContextPath();
    String path = uri.substring(context.length());

    return convertToEncoding(path);
  }

  protected String convertToEncoding(String value) {
    if (null != value) {
      String encoding = getCharacterEncoding();

      if (null == encoding)
        encoding = "UTF-8";

      if (!encoding.equalsIgnoreCase("iso-8859-1"))
        try {
          value = new String(value.getBytes("iso-8859-1"), encoding);

        } catch (UnsupportedEncodingException ex) {
          Logger.getLogger(CustomHttpServletRequest.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    return value;
  }
}
